package maldade.configuration;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.lang.StringEscapeUtils;

/**
 * Message loader singleton.
 * 
 * @author rnojiri
 */
public class MessageLoader
{
	private final static String ATTR_MESSAGE_LIST = "messageList";
	
	private PropertiesConfiguration configuration;
	
	private static MessageLoader instance;
	
	/**
	 * Loads a configuration file from a given path.
	 * 
	 * @param filePath
	 * @throws Exception
	 */
	private MessageLoader(String filePath) throws Exception
	{
		if(filePath == null)
		{
			throw new Exception("File path configuration cannot be null.");
		}
		
		configuration = new PropertiesConfiguration(filePath);
		
		configuration.setAutoSave(false);
		configuration.setReloadingStrategy(new FileChangedReloadingStrategy());
	}
	
	/**
	 * Initializes this instance.
	 * 
	 * @param filePath
	 * @throws Exception
	 */
	public static void initialize(String filePath) throws Exception
	{
		if(instance == null)
		{
			instance = new MessageLoader(filePath);
		}
	}
	
	/**
	 * Returns the instance.
	 * 
	 * @return ConfigurationLoader
	 */
	public static MessageLoader getInstance()
	{
		return instance;
	}
	
	/**
	 * Adds a message to the request.
	 * 
	 * @param message
	 */
	@SuppressWarnings("unchecked")
	public void addMessage(EMessages message, HttpServletRequest request)
	{
		List<String> messageList = (List<String>)request.getAttribute(ATTR_MESSAGE_LIST);
		
		if(messageList == null)
		{
			messageList = new ArrayList<String>();
		}
		
		messageList.add(StringEscapeUtils.escapeHtml(configuration.getString(message.toString())));
		
		request.setAttribute(ATTR_MESSAGE_LIST, messageList);
	}
}
